package com.hcb.utils;

import com.hcb.pojo.User;
import io.jsonwebtoken.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

public class JwtUtil {
    public static String secret="hcbjwt";
    public static String buildToken(User user){
        JwtBuilder jwtBuilder= Jwts.builder();
        String token=jwtBuilder
                .claim("userId",user.getId())
                .signWith(SignatureAlgorithm.HS256,secret)
                .compact();
        return token;
    }
    public static Map getUser(String token){
        JwtParser parser=Jwts.parser();
        Claims claims=parser.setSigningKey(secret).parseClaimsJws(token).getBody();
        return (Map) claims.get("user");
    }
    public static int getUserId(String token){
        JwtParser parser=Jwts.parser();
        Claims claims=parser.setSigningKey(secret).parseClaimsJws(token).getBody();
        return (int) claims.get("userId");
    }
    public static int getUserId(HttpServletRequest request){
        String token=request.getHeader("token");
        JwtParser parser=Jwts.parser();
        Claims claims=parser.setSigningKey(secret).parseClaimsJws(token).getBody();
        return (int) claims.get("userId");
    }
}
